package com.cloudcross.ssp.web.advertiser.main.ad;

import com.cloudcross.ssp.base.utils.freemarker.FreemarkerTemplateProcessor;
import com.cloudcross.ssp.base.web.SimpleController;
import com.cloudcross.ssp.base.web.result.AjaxResult;
import com.cloudcross.ssp.common.consts.Status;
import com.cloudcross.ssp.common.utils.Common;
import com.cloudcross.ssp.common.utils.LangUtil;
import com.cloudcross.ssp.common.utils.Pager;
import com.cloudcross.ssp.model.Account;
import com.cloudcross.ssp.model.Advertiser;
import com.cloudcross.ssp.model.Log;
import com.cloudcross.ssp.service.IAdvAgentService;
import com.cloudcross.ssp.service.IAdvertiserService;
import com.cloudcross.ssp.service.ILogService;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/advertiser/main/ad/advertiser")
public class AdvertiserController extends SimpleController {
	@Autowired
	protected IAdvertiserService advertiserService;
	@Autowired
	private ILogService logService;

	@Autowired
	private FreemarkerTemplateProcessor templateProcessor;
	@Autowired
	private IAdvAgentService advAgentService;
	/**
	 * @return 返回到广告主管理第一页。
	 */
	@RequestMapping
	public String index(Model model) {
		model.addAttribute("status",new Long(2));
		model.addAttribute("industryId", new Integer(0));
		return redirect(page("list"));
	}
	
	/**
	 * 
	 * @param model
	 * @param paramMap
	 * @param status 投放的状态：-1（删除）【不在界面显示】，0（正常），1（停用），2（全部）【只在界面显示】
	 * @param page
	 * @return
	 */
	@RequestMapping("/list")
	public String list(Model model,@RequestParam HashMap<String, Object> paramMap,@RequestParam(defaultValue="2") int status,@RequestParam(defaultValue="1") int page) {
		Map<String,Object>condition = new HashMap<String,Object>();
		Account account = getLoginUser();
		condition.put("agentId", account.getAgentId());
		
		Object obj = paramMap.get("searchValue");
		if(null != obj){
			String searchValue = String.valueOf(obj).trim();
			condition.put("searchValue", "%"+searchValue+"%");
			//searchValue = new String(String.valueOf(obj).trim().getBytes("ISO-8859-1"),"UTF-8");
		}
		
		//按状态搜索用 2--全部
		if(status != 2){}
		if(status != 2){
			//状态为0，1，按状态查询
			condition.put("status", new Integer(status));
			model.addAttribute("status",new Integer(status));
		}
		
		Object industryFatherIdObj = paramMap.get("industryId");
		if(industryFatherIdObj!=null && !"".equals(industryFatherIdObj) && !"0".equals(industryFatherIdObj)){
			condition.put("industryFatherId", Integer.parseInt(industryFatherIdObj.toString()));
		}
		
		
		int totalRow = advertiserService.countByParams(condition);
		
		// 查询总行数
		Pager pager = new Pager();
		pager.setPage(page);
		pager.setTotalRow(totalRow);
		
		List<Advertiser> advertiserList = advertiserService.findByParams(condition, pager);
		if(paramMap.get("status")==null){
			paramMap.put("status", new Integer(2));
		}
		if(paramMap.get("industryId")==null){
			paramMap.put("industryId",new Long(0));
		}
		model.addAllAttributes(paramMap);
		model.addAttribute("pager", pager);
		model.addAttribute("advertiserList", advertiserList);
		return page("list");
	}
	
	/**
	 * 广告主编辑
	 * @param request
	 * @param model
	 * @param id 广告主ID
	 * @return
	 */
	@RequestMapping("/edit/{id}")
	public String edit(HttpServletRequest request,Model model, @PathVariable long id) {
		//todo：可以用一条sql来查询（待做）
		Advertiser advertiser = advertiserService.findById(id);
		model.addAttribute("industryIds", advertiser.getIndustryIds());
		model.addAttribute("sessionid", request.getSession().getId());
		model.addAttribute("advertiser", advertiser);
		return page("edit");
	}	
	/**
	 * @return 创建广告主账号。
	 */
	@RequestMapping("/create")
	public String create(HttpServletRequest request,Model model) {
		model.addAttribute("sessionid", request.getSession().getId());
		Account account = getLoginUser();
		if (account != null){
			model.addAttribute("agentId",account.getAgentId());
		}
		return page("create");
	}
	
	@RequestMapping("/update")
	public String update(Model model,@RequestParam Long advertiserId,@RequestParam(defaultValue = "1") int page) {
		Map<String,Object> condition = new HashMap<String,Object>();//存放查询条件
		condition.put("tableName", "t_advertiser");
		condition.put("recordId", advertiserId);
		int totalRow = logService.findLogCountByCondition(condition);
		Pager pager = new Pager();
		pager.setPage(page);
		pager.setTotalRow(totalRow);		
		List<Log> logList = logService.findLogByCondition(condition, pager);
		
		model.addAttribute("pager", pager);
		model.addAttribute("logList", logList);
		model.addAttribute("advertiserId", advertiserId);
		return page("update");
	}
	
	/**
	 * 添加或修改的保存
	 * @param model
	 * @param t
	 * @param request
	 * @return
	 */
	@RequestMapping("/save")
	public String save(Model model,@ModelAttribute("form") Advertiser t,HttpServletRequest request) {
		//添加广告主ID为空
		if (t.getId() == null) {
			Account account = getLoginUser();
			if (account.getOperatorId()!=0){
				//如果获取的当前执行操作的账号的operatorId不等于0，那么，对应的广告主也要插入不等于0的operatorId。
				t.setOperatorId(account.getOperatorId());
			}else {
				t.setOperatorId(new Long(0));
			}
		} else {
			Advertiser formerAdvertiser = advertiserService.findById(t.getId());
			if (advertiserService.edit(t)){
				String s =t.getName()+"：";
				if (!formerAdvertiser.getName().equals(t.getName())) {
					s=s.concat("广告主名  "+formerAdvertiser.getName()+" > "+t.getName()+" / ");
					}
				if (!formerAdvertiser.getHomePage().equals(t.getHomePage())) {
					s=s.concat("网址  "+formerAdvertiser.getHomePage()+" > "+t.getHomePage()+" / ");
					}
				
				if (!formerAdvertiser.getRegName().equals(t.getRegName())) {
					s=s.concat("公司名  "+formerAdvertiser.getRegName()+" > "+t.getRegName()+" ");
					}
				
				if (!formerAdvertiser.getContacts().equals(t.getContacts())) {
					s=s.concat("联系人  "+formerAdvertiser.getContacts()+" > "+t.getContacts()+" / ");
					}
				if (!formerAdvertiser.getTel().equals(t.getTel())) {
					s=s.concat("电话  "+formerAdvertiser.getTel()+" > "+t.getTel()+" / ");
					}
				
				if (!formerAdvertiser.getEmail().equals(t.getEmail())) {
					s=s.concat("邮箱  "+formerAdvertiser.getEmail()+" > "+t.getEmail()+" / ");
					}
				
				if (!formerAdvertiser.getMemo().equals(t.getMemo())) {
					s=s.concat("备注  "+formerAdvertiser.getMemo()+" > "+t.getMemo());
				}
				//如果编辑广告主成功，向log数据库中插入记录
				Log logModify= new Log();
				logModify.setModule("Advertiser");//对应模块
				logModify.setTableName("t_advertiser");//对应的表名
				logModify.setRecordId(t.getId());//对应广告主id
				logModify.setActionType("编辑");	//操作类型
				logModify.setAction(s);//变更详情
				//下面这几个字段目前后端数据没有得到。所以仅作测试用！
				logModify.setActionTime("100");
				logModify.setAccountId(Long.valueOf(getLoginUser().getId()));
				logModify.setUserIp(Common.toIpAddr(request));
				logModify.setAccountName(getLoginUser().getAccountName());
				logService.add(logModify); 	
			}
		}
		// 跳转到管理页面。
		return redirect(page("list"));
	}
	@RequestMapping("enable")
	public @ResponseBody String enable(Long[] id,HttpServletRequest request) {
		Date date = null;
		if (ArrayUtils.isNotEmpty(id)) {
			List<String> list =new ArrayList<String>();
			for (int i = 0; i < id.length; i++) {
				Advertiser advertiser = advertiserService.findById(new Long(id[i]));
				list.add(advertiser.getName());
			}
			//获取当前系统时间，向后台传，确保所有的时间保持一致
			date = new Date();
			if (advertiserService.updateStatus(LangUtil.array2List(id),Status.enable.value)){
				advertiserService.updateSupdatedAll(LangUtil.array2List(id),date);
				for (int i = 0; i < list.size(); i++) {
					Log log =new Log();
					log.setModule("Advertiser");//对应模块
					log.setTableName("t_advertiser");//对应的表名
					log.setRecordId(id[i]);//对应订单id
					log.setActionType("启用");	//操作类型
					log.setAction("启用广告主: "+list.get(i));//变更详情,广告主名称
					//下面这几个字段目前后端数据没有得到。所以仅作测试用！
					log.setActionTime("100");
					log.setAccountId(Long.valueOf(getLoginUser().getId()));
					log.setUserIp(Common.toIpAddr(request));
					log.setAccountName(getLoginUser().getAccountName());
					logService.add(log);
				}
			}
		}
		return OK;
	}
	
	@RequestMapping("disable")
	public @ResponseBody String disable(Long[] id,HttpServletRequest request) {
		Date date = null;//保存当前系统时间
		if (ArrayUtils.isNotEmpty(id)) {
			//循环得到订单名称（批量或者单个都可以）___为了插入log记录的时候显示订单名称！_
			List<String> list = new ArrayList<String>();
			for (int i = 0;i < id.length;i++) {
				Advertiser advertiser = advertiserService.findById(new Long(id[i]));
				list.add(advertiser.getName());
			}
			date = new Date();
			if( advertiserService.updateStatus(LangUtil.array2List(id),Status.disable.value) ) {
				advertiserService.updateSupdatedAll(LangUtil.array2List(id),date);
				//如果禁用订单成功，向log数据库中插入记录！
				for (int i = 0;i < id.length;i++) {
				Log log= new Log();
				log.setModule("Advertiser");//对应模块
				log.setTableName("t_advertiser");//对应的表名
				log.setRecordId(id[i]);//对应订单id
				log.setActionType("停用");	//操作类型
				log.setAction("停用广告主: "+list.get(i));//变更详情,订单名称
				//下面这几个字段目前后端数据没有得到。所以仅作测试用！
				log.setActionTime("100");
				log.setAccountId(Long.valueOf(getLoginUser().getId()));
				log.setUserIp(Common.toIpAddr(request));
				log.setAccountName(getLoginUser().getAccountName());
				logService.add(log);
				}
			}
		}
		return OK;
	}
	
	@RequestMapping("delete")
	public @ResponseBody String delete(Long[] id,HttpServletRequest request) {
		if (ArrayUtils.isNotEmpty(id)) {
			//循环得到订单名称（批量或者单个都可以）_________为了插入log记录的时候显示订单名称！
			List<String> list = new ArrayList<String>();
			
			for (int i = 0;i < id.length;i++) {
				Advertiser a = advertiserService.findById(new Long(id[i]));
				list.add(a.getName());
			}
			
			if(advertiserService.updateStatusAll(LangUtil.array2List(id),Status.delete.value) ) {
				//如果删除订单成功，向log数据库中插入记录！
				for (int i = 0;i < id.length;i++) {
				Log logDel= new Log();
				logDel.setModule("Advertiser");//对应模块
				logDel.setTableName("t_advertiser");//对应的表名
				logDel.setRecordId(id[i]);//对应广告主id
				logDel.setActionType("删除");	//操作类型
				logDel.setAction("删除了广告主:"+list.get(i));//变更详情
				//下面这几个字段目前后端数据没有得到。所以仅作测试用！
				logDel.setActionTime("100");
				logDel.setAccountId(Long.valueOf(getLoginUser().getId()));
				logDel.setUserIp(Common.toIpAddr(request));
				logDel.setAccountName(getLoginUser().getAccountName());
				logService.add(logDel);
				}
				
			}
		}
		return OK;
	}
	

	private String getStatusStr(int status){
		if(status == 0){
			return "正常";
		}else if(status == 1){
			return "停用";
		}else if(status == 2){
			return "全部";
		}else{
		return "";
		}
	}
	//导出advertiser列表页Excel用
	@RequestMapping("/exportDataReportExcel")
	public void exportDataReportExcel(HttpServletResponse response,@RequestParam(defaultValue="2") int status,@RequestParam(defaultValue="0") Long industryId,String searchValue) {
		Map<String,Object>condition = new HashMap<String,Object>();
		//筛选条件
		//行业 默认全部
		if(industryId != 0){
			condition.put("industryId", industryId);
		}else{
			condition.put("industryName", "全部");
		}
		//按状态搜索用
		if (status != 2){
			condition.put("status", status);
			condition.put("statusName", getStatusStr(status));
		}else{
			condition.put("statusName", "全部");
		}
		if(StringUtils.isNotBlank(searchValue)){
			try {
				searchValue = new String(searchValue.trim().getBytes("ISO-8859-1"),"UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			condition.put("searchValueStr",searchValue.trim());
			condition.put("value", "%"+searchValue.trim()+"%");
			
		}
		Account account = getLoginUser();
		condition.put("agentId", account.getAgentId());
		
		/**
		* 参数和list里要一样
		*/
		List<Advertiser> reportList = advertiserService.findByParams(condition, null);
		String agentName = advAgentService.findById(account.getAgentId()).getName();
		condition.put("agentName", agentName);
		condition.put("dataList", reportList);
		response.reset();
		// Content-Type:application/vnd.ms-excel;charset=utf8或者text/xml;charset=utf8
		response.setContentType("application/vnd.ms-excel;charset=utf8");
		// 设置excel文件名称
		SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
		String fileName = "Advertiser" + df2.format(new Date());
		response.setHeader("Content-Disposition", "attachment;filename="+ fileName + ".xls");
		// 需要对excel的列和行的总数进行指定
		int column = 9;
		condition.put("dataSize", (reportList.size() + 100));
		condition.put("column", column);
		/*String name = this.advertiserService.selectAdvertiserNameById(advertiserId);
		condition.put("message","广告主"+name+"修改记录");*/
		String excelOrder = templateProcessor.processTemplate("excel/advertiserDataReport.ftl", condition);
		try {
			PrintWriter out = response.getWriter();
			out.write(excelOrder);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
		
	//导出日志Excel用
	@RequestMapping("/exportLogExcel")
	public void exportLogExcel(HttpServletResponse response,@RequestParam Long advertiserId) {
		Map<String,Object> condition = new HashMap<String,Object>();//存放查询条件
		condition.put("tableName", "t_advertiser");
		condition.put("recordId", advertiserId);
		List<Log> logList = logService.findLogByCondition(condition, null);
		condition.put("dataList", logList);
		response.reset();
		// Content-Type:application/vnd.ms-excel;charset=utf8或者text/xml;charset=utf8
		response.setContentType("application/vnd.ms-excel;charset=utf8");
		// 设置excel文件名称
		SimpleDateFormat df2 = new SimpleDateFormat("yyyyMMddHHmmss");
		String fileName = "advertiserLog" + df2.format(new Date());
		response.setHeader("Content-Disposition", "attachment;filename="+ fileName + ".xls");
		// 需要对excel的列和行的总数进行指定
		int column = 6;
		condition.put("dataSize", (logList.size() + 100));
		condition.put("column", column);
		String name = this.advertiserService.selectAdvertiserNameById(advertiserId);
		condition.put("message","广告主"+name+"修改记录");
		String excelOrder = templateProcessor.processTemplate("excel/logReport.ftl", condition);
		try {
			PrintWriter out = response.getWriter();
			out.write(excelOrder);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
			
	@RequestMapping("/fileUpload")
	@ResponseBody
	public AjaxResult fileUpload(HttpServletRequest request,HttpServletResponse response) {
		return this.advertiserService.fileUpload(request, response);	
	}
}
